package com.hxzy.controller.vue.employee;

import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.PageResp;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.MarketingThreadLocalUtil;
import com.hxzy.common.wrap.PageInfoUtil;
import com.hxzy.controller.vue.employee.req.EmployeeAddReq;
import com.hxzy.controller.vue.employee.req.EmployeeEditReq;
import com.hxzy.controller.vue.employee.req.EmployeePwdReq;
import com.hxzy.controller.vue.employee.req.EmployeeReq;
import com.hxzy.controller.vue.employee.resp.EmployeeExcelResp;
import com.hxzy.controller.vue.employee.resp.EmployeeResp;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import com.hxzy.controller.vue.mapstruct.EmployeeConvert;
import com.hxzy.entity.Employee;
import com.hxzy.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/8/31 15:56
 * @Version 1.0
 */
@RequestMapping(value = "/api/employee")
@RestController
@Api(tags = "后台-管理员")
public class EmployeeController {

    @Autowired
    private EmployeeService  employeeService;

    @GetMapping(value = "/data")
    @ApiOperation(value = "分页查询")
    public R<PageResp<EmployeeResp>> search(@Valid EmployeeReq req){
        PageInfo<EmployeeResp> pageInfo=this.employeeService.search(req);
        PageResp<EmployeeResp> resp = PageInfoUtil.pageInfoToResp(pageInfo);
        return R.okHasData(resp);
    }

    @ApiOperation(value = "新增")
    @PostMapping
    public R add(@RequestBody @Valid EmployeeAddReq req){
        if(!req.getLoginPwd().equals(req.getLoginConfirmPwd())){
            return R.build(AckCode.SET_PASSWORD_INVALID);
        }
        String pwd= BCrypt.hashpw(req.getLoginPwd());
        req.setLoginPwd(pwd);

        //方案1，使用BeanUtils   80%的公司
        // Employee entity=new Employee();
        // BeanUtils.copyProperties(req,entity);

        //方案2 mapstruct   5%的公司用
        Employee entity = EmployeeConvert.INSTANCE.convert(req);
        entity.setRoot("0");

        //保存账号唯一性的验证
        boolean exists=this.employeeService.existsValue(Employee::getLoginName,entity.getLoginName(), entity.getId());
        if(exists){
            return R.build(AckCode.EXISTS_VALUE_ACCOUNT);
        }

        boolean save = this.employeeService.save(entity);
        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R<EmployeeResp>  findById(@PathVariable(value = "id") Long id){
        Employee db = this.employeeService.getById(id);
        if(Objects.isNull(db)){
            return R.build(AckCode.NOT_FOUND_DATA);
        }
        //转换对象
        EmployeeResp convert = EmployeeConvert.INSTANCE.convert(db);
        return R.okHasData(convert);
    }

    @ApiOperation(value = "修改")
    @PutMapping
    public R update(@RequestBody @Valid EmployeeEditReq req){
        Employee db = this.employeeService.getById(req.getId());
        if(Objects.isNull(db)){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        //当前登录谁登录的
        AdminLoginResp  adminLoginResp= MarketingThreadLocalUtil.adminThreadLocal.get();

        //只有超级管理员才能改状态
        if(Objects.nonNull(req.getStatus())){
            if(!adminLoginResp.getRoot().equals("1")){
                return R.build(AckCode.PERMISSION_NOT_STATE_EDIT);
            }
        }
        db.setAvatar(req.getAvatar());
        db.setGender(req.getGender());
        db.setStatus(req.getStatus());
        boolean save = this.employeeService.updateById(db);
        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @ApiOperation(value = "更改密码")
    @PostMapping(value = "/change/password")
    public R changePwd(@RequestBody @Valid EmployeePwdReq req){
        if(!req.getPassword().equals(req.getConfirmPwd())){
            return R.build(AckCode.SET_PASSWORD_INVALID);
        }
        //管理员允许更改所有的人密码，非管理员只能更改自己的密码
        AdminLoginResp adminLoginResp=MarketingThreadLocalUtil.adminThreadLocal.get();
        //非管理员，并且不是自己，不允许修改     true &&
        if(adminLoginResp.getRoot().equals("0") && req.getId().intValue()!= adminLoginResp.getId().intValue()){
            return R.build(AckCode.PERMISSION_NOT_PASSWORD_EDIT);
        }

        boolean result=this.employeeService.changePassword(req.getId(),req.getPassword());

        return result? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @PostMapping(value = "/excel" )
    @ApiOperation(value = "excel下载",produces =  MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void search(EmployeeReq req, HttpServletResponse response) throws IOException {
        List<Employee> employeeList = this.employeeService.excelDownload(req);
        //数据转换
        List<EmployeeExcelResp> convert = EmployeeConvert.INSTANCE.convert(employeeList);

        //写放到服务器响应流
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("employee_"+ UUID.randomUUID().toString(), "UTF-8").replaceAll("\\+", "%20");
        //告诉浏览，需要二进制文件方式发送给客户端
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        //easyExcel的操作
        EasyExcel.write(response.getOutputStream(), EmployeeExcelResp.class).sheet().doWrite(convert);
    }
}
